package com.chen.music.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.music.model.Collect;
import com.chen.music.model.Comment;
import com.chen.music.model.ListSong;
import com.chen.music.model.Song;
import com.chen.music.service.CollectService;
import com.chen.music.service.CommentService;
import com.chen.music.service.ListSongService;
import com.chen.music.service.SongService;
import com.chen.music.util.CommonResult;
import com.chen.music.util.MessageConst;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 歌曲 前端控制器
 * </p>
 *
 * @author boat
 * @since 2022-01-13
 */
@RestController
@RequestMapping("/song")
@Api(tags = "歌曲管理")
public class SongController {

    @Autowired
    private SongService songService;

    @Autowired
    private ListSongService listSongService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private CollectService collectService;

    @PostMapping("/add")
    @ApiOperation("新增歌曲")
    public CommonResult add(@RequestParam("file") MultipartFile multipartFile, Song song) {
        if (multipartFile.isEmpty()) {
            return new CommonResult(200, false, MessageConst.ADD_SONG_FAIL);
        }
        String fileName = System.currentTimeMillis() + multipartFile.getOriginalFilename();
        String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "song";
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdir();
        }
        //上传后的文件地址
        File realPath = new File(filePath + System.getProperty("file.separator") + fileName);
        try {
            multipartFile.transferTo(realPath);
            song.setUrl("/song/" + fileName); //更新数据库文件的相对地址
            if (songService.save(song)) {
                return new CommonResult(200, true, MessageConst.ADD_SONG_SUCCESS);
            }
            return new CommonResult(200, false, MessageConst.ADD_SONG_FAIL);
        } catch (IOException e) {
            e.printStackTrace();
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    @GetMapping("/{currentPage}/{pageSize}")
    @ApiOperation("歌曲检索")
    public CommonResult findByPage(@PathVariable(value = "currentPage") Integer currentPage, @PathVariable(value = "pageSize") Integer pageSize, Song song) {
        try {
            Page<Song> page = songService.page(new Page<>(currentPage, pageSize), getWrapper(song));
            if (currentPage > page.getPages()) { //判断当前也是否大于总页数
                return new CommonResult(200, true, songService.page(new Page<>(page.getPages(), pageSize), getWrapper(song)));
            }
            return new CommonResult(200, true, songService.page(new Page<>(currentPage, pageSize), getWrapper(song)));
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }


    @DeleteMapping("/delete/{idx}")
    @ApiOperation("删除歌曲")
    public CommonResult delete(@PathVariable("idx") String ids) {
        try {
            for (String id : Arrays.asList(ids)) {
                Song song = songService.getById(Integer.parseInt(id));
                Map<String, Object> map = new HashMap<>();
                map.put("song_id", Integer.parseInt(id));
                File mp3File = new File(System.getProperty("user.dir") + song.getUrl());
                File picFile = new File(System.getProperty("user.dir") + song.getPic());
                List<ListSong> listSongs = listSongService.listByMap(map);
                if (listSongs != null && listSongs.size() > 0) {
                    listSongService.removeByMap(map);
                }
                List<Comment> comments = commentService.listByMap(map);
                if (comments != null && comments.size() > 0) {
                    commentService.removeByMap(map);
                }
                List<Collect> collects = collectService.listByMap(map);
                if (collects != null && collects.size() > 0) {
                    collectService.removeByMap(map);
                }
                if (songService.removeById(song.getId())) {
                    if (mp3File.exists() && picFile.exists()) {
                        mp3File.delete();
                        picFile.delete();
                    }
                }
            }
            return new CommonResult(200, true, MessageConst.DELETE_SONG_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(500, false, MessageConst.DELETE_SONG_FAIL);
        }
    }

    @PutMapping("/update")
    @ApiOperation("更新歌曲")
    public CommonResult update(Song song) {
        try {
            if (songService.updateById(song)) {
                return new CommonResult(200, true, MessageConst.UPDATE_SONG_SUCCESS);
            }
            return new CommonResult(200, false, MessageConst.UPDATE_SONG_FAIL);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    @PostMapping("/update/img/{id}")
    @ApiOperation("更新歌曲图片")
    public CommonResult updateImg(@RequestParam("file") MultipartFile multipartFile, @PathVariable("id") Integer id) {
        if (multipartFile.isEmpty()) {
            return new CommonResult(200, false, MessageConst.UPDATE_SONG_IMG_FAIL);
        }
        String fileName = System.currentTimeMillis() + multipartFile.getOriginalFilename();
        String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "img" + System.getProperty("file.separator")
                + "songPic"; //文件路径
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdir();
        }
        //上传后的文件地址
        File realPath = new File(filePath + System.getProperty("file.separator") + fileName);
        try {
            multipartFile.transferTo(realPath);
            Song song = songService.getById(id);
            //删除原文件
            File picFile = new File(System.getProperty("user.dir") + song.getPic());
            if (picFile.exists()) {
                picFile.delete();
            }
            song.setPic("/img/songPic/" + fileName); //更新数据库文件的相对地址
            if (songService.updateById(song)) {
                return new CommonResult(200, true, MessageConst.UPDATE_SONG_IMG_SUCCESS);
            }
            return new CommonResult(200, false, MessageConst.UPDATE_SONG_IMG_FAIL);
        } catch (IOException e) {
            e.printStackTrace();
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    @PostMapping("/update/file/{id}")
    @ApiOperation("更新歌曲文件")
    public CommonResult updateMp3(@RequestParam("file") MultipartFile multipartFile, @PathVariable("id") Integer id) {
        if (multipartFile.isEmpty()) {
            return new CommonResult(200, false, MessageConst.UPDATE_SONG_FILE_FAIL);
        }
        String fileName = System.currentTimeMillis() + multipartFile.getOriginalFilename();
        String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "song";
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdir();
        }
        //上传后的文件地址
        File realPath = new File(filePath + System.getProperty("file.separator") + fileName);
        try {
            multipartFile.transferTo(realPath);
            Song song = songService.getById(id);
            //删除原文件
            File mp3File = new File(System.getProperty("user.dir") + song.getUrl());
            if (mp3File.exists()) {
                mp3File.delete();
            }
            song.setUrl("/song/" + fileName); //更新数据库文件的相对地址
            if (songService.updateById(song)) {
                return new CommonResult(200, true, MessageConst.UPDATE_SONG_FILE_SUCCESS);
            }
            return new CommonResult(200, false, MessageConst.UPDATE_SONG_FILE_FAIL);
        } catch (IOException e) {
            e.printStackTrace();
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    @GetMapping("/{name}")
    @ApiOperation("根据歌名获取歌曲id")
    public CommonResult findByName(@PathVariable("name") String name) {
        LambdaQueryWrapper<Song> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(!StringUtils.isEmpty(name), Song::getName, name);
        try {
            List<Song> list = songService.list(wrapper);
            if (list == null || list.size() <= 0) {
                return new CommonResult(200, false);
            }
            return new CommonResult(200, true, list);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    @GetMapping("/detail/{id}")
    @ApiOperation("根据id获取歌曲详情")
    public CommonResult findById(@PathVariable("id") Integer id) {
        try {
            return new CommonResult(200, true, songService.getById(id));
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    @GetMapping
    @ApiOperation("统计歌曲数量")
    public CommonResult count() {
        try {
            return new CommonResult(200, true, songService.count());
        } catch (Exception e) {
            return new CommonResult(500, false, MessageConst.INTERFACE_EXCEPTION);
        }
    }

    //封装查询条件
    private LambdaQueryWrapper<Song> getWrapper(Song song) {
        LambdaQueryWrapper<Song> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(song.getSingerId() != null, Song::getSingerId, song.getSingerId());
        wrapper.like(!StringUtils.isEmpty(song.getName()), Song::getName, song.getName());
        wrapper.like(!StringUtils.isEmpty(song.getIntroduction()), Song::getIntroduction, song.getIntroduction());
        return wrapper;
    }
}

